package discovery

import (
	"bytes"
	"encoding/json"
	"github.com/goinggo/mapstructure"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
)

type Agent struct {
	AgentId       string
	Host          string
	UpdateTime    int64
	ProxyServices []ProxyService
}

type ProxyService struct {
	ServiceName string
	Host        string
	Ports       []Port
}

type Port struct {
	Protocol string
	Port     int32
}

func RegisterAgent() {
	url := GetThomasUrl() + "/agents"
	request, _ := http.NewRequest(http.MethodPut, url, nil)
	// client需要分开
	resp, error := DiscoveryHttpClient.Do(request)
	if error != nil {
		log.Error(error)
	}
	if resp != nil {
		defer resp.Body.Close()
		body, _ := ioutil.ReadAll(resp.Body)
		var response WebResponse
		json.Unmarshal(body, &response)
		mapstructure.Decode(response.Data, &AgentInfo)
	}
}

func RegisterWithConagent() {
	url := GetThomasUrl() + "/conagent/api/v1/service/register"
	req := ConagentRegisterReq{
		AppId:    "thomas-mesh",
		Port:     9333,
		Protocol: "http",
		Check: CheckInfo{
			Type:            "",
			Http:            "http://undefined:9333/ping",
			Method:          "",
			Interval:        0,
			Timeout:         0,
			DeregisterAfter: 0,
		},
		Tags:           []string{"Go"},
		PackageVersion: "",
		Cluster:        "develop35",
		Project:        "thomas",
		Dc:             "cn-shanghai",
	}
	body, _ := json.Marshal(req)
	buf := bytes.NewBuffer(body)
	request, _ := http.NewRequest(http.MethodPut, url, buf)
	resp, error := DiscoveryHttpClient.Do(request)
	if error != nil {
		log.Error(error)
	} else {
		defer resp.Body.Close()
		body, _ := ioutil.ReadAll(resp.Body)
		var response WebResponse
		json.Unmarshal(body, &response)
		log.Debug(response)
	}
}
